package com.aierkeji.call.cms.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.aierkeji.call.cms.contants.Contants;
import com.aierkeji.call.cms.dao.jpa.AkjCallClueGroupDao;
import com.aierkeji.call.cms.dao.jpa.AkjCallReportDao;
import com.aierkeji.call.cms.entity.AkjCallUser;
import com.aierkeji.call.cms.entity.vo.AkjCallClueStatisticsVo;
import com.aierkeji.call.cms.entity.vo.AkjCallClueVo;
import com.aierkeji.call.cms.entity.vo.SearchOptionsVo;
import com.aierkeji.call.cms.util.CsvUtils;
import com.aierkeji.call.cms.util.DateTimeUtils;
import com.aierkeji.call.cms.util.PageUtils;
import com.aierkeji.call.cms.util.ResultMapHelper;
import com.aierkeji.call.cms.util.StringUtils;

@Service
public class AkjCallReportService {
	private final Logger log = LogManager.getLogger(getClass());
	private String[] reportList = { "统计日期", "坐席", "任务总数", " 通话时长", "已拨打总数", "净拨打总数", "未拨打总数", "呼通数", "未通数", "无意向总数",
			"同意总数", "待跟进总数" };
	@Autowired
	AkjCallReportDao akjCallReportDao;
	@Autowired
	AkjCallUserService akjCallUserService;

	@Autowired
	private AkjCallClueGroupDao akjCallClueGroupDao;

	public Map<String, Object> report(int pageNo, Map<String, Object> map, boolean isTabel) {
		// TODO Auto-generated method stub
		String type = (String) map.get("type");// 报表类型：自己的报表，下级的报表
		String assigneTo = (String) map.get("assigneTo");//
		String staticDate = (String) map.get("staticDate");//
		String leaderId = (String) map.get("leaderId");//
		String groupIdStr = (String) map.get("groupId");//
		String pageSizeStr = (String) map.get("pageSize");
		if (StringUtils.isEmpty(staticDate)) {
			return ResultMapHelper.nullParamsResult();
		}
		Date date = DateTimeUtils.converStringToDate(staticDate);
		if (date == null) {
			return ResultMapHelper.nullParamsResult();
		}
		Long groupId = StringUtils.converStringToLong(groupIdStr);
		int pageSize = StringUtils.isEmpty(pageSizeStr) ? Contants.PAGE_SIZE : Integer.parseInt(pageSizeStr);

		Subject subject = SecurityUtils.getSubject();
		AkjCallUser akjCallUser = (AkjCallUser) subject.getSession().getAttribute("loginUser");
		if ("my".equals(type)) {// 我的报表
			return myReport(date, groupId, pageNo, pageSize);
		}
		boolean salesflag = akjCallUser.checkRole(Contants.ROLE_ID_SALES);
		boolean managerflag = akjCallUser.checkRole(Contants.ROLE_ID_MANAGER);
		boolean statisflag = akjCallUser.checkRole(Contants.ROLE_ID_STATISTICIAN);
		Long assigneToId = salesflag ? akjCallUser.getId() : StringUtils.converStringToLong(assigneTo);
		Long leaderIdLong = salesflag ? null
				: managerflag ? akjCallUser.getId() :statisflag?akjCallUser.getLeaderId(): StringUtils.converStringToLong(leaderId);
		Page<AkjCallClueStatisticsVo> list = null;
		if (isTabel) {
			list = akjCallReportDao.getSubReport(date, assigneToId, leaderIdLong, groupId, pageNo, pageSize);
		} else {
			if ((managerflag||statisflag) && StringUtils.isEmpty(assigneTo)) {// 如果是企业管理员，下级报表，没有选择下级，则出所有得统计之和
				list = akjCallReportDao.getReport(date, null, leaderIdLong, groupId, pageNo, pageSize);
			} else {
				list = akjCallReportDao.getSubReport(date, assigneToId, leaderIdLong, groupId, pageNo, pageSize);
			}
		}
		return ResultMapHelper.success(list);
	}

	public Map<String, Object> myReport(Date date, Long groupId, int pageNo, int pageSize) {
		Subject subject = SecurityUtils.getSubject();
		AkjCallUser akjCallUser = (AkjCallUser) subject.getSession().getAttribute("loginUser");
		Page<AkjCallClueStatisticsVo> list = null;
		if (akjCallUser.checkRole(Contants.ROLE_ID_MANAGER)) {
//			list = akjCallReportDao.getReport(date,null, akjCallUser.getId(), groupId, pageNo, pageSize);
			// 我得报表，企业管理员是没有数据得
			PageRequest pageRequest = PageUtils.buildPageRequestNoSort(1, pageSize);
			list = new PageImpl<AkjCallClueStatisticsVo>(new ArrayList<AkjCallClueStatisticsVo>(), pageRequest, 0);
		} else if (akjCallUser.checkRole(Contants.ROLE_ID_SALES)) {
			list = akjCallReportDao.getReport(date, akjCallUser.getId(), null, groupId, pageNo, pageSize);
		}

		return ResultMapHelper.success(list);
	}

	public Map<String, Object> getQueryConfig() {
		// TODO Auto-generated method stub
		Subject subject = SecurityUtils.getSubject();
		AkjCallUser akjCallUser = (AkjCallUser) subject.getSession().getAttribute("loginUser");
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("now", DateTimeUtils.converDateToString(new Date(), DateTimeUtils.DATE_PATTERN_DAY));
		if (akjCallUser.checkRole(Contants.ROLE_ID_SALES)) {
			return ResultMapHelper.success(dataMap);
		}
		List<SearchOptionsVo> searchAssigneTos = akjCallUserService.findCanAssigneUser(null);
		AkjCallUser queryUser = new AkjCallUser();
		if(akjCallUser.checkRole(Contants.ROLE_ID_STATISTICIAN)) {
			queryUser.setId(akjCallUser.getLeaderId());
		}else {
			queryUser.setId(akjCallUser.getId());	
		}
		List<SearchOptionsVo> groupList = akjCallClueGroupDao.findSelectCallClueGroup(queryUser);

		dataMap.put("searchAssigneTos", searchAssigneTos);
		dataMap.put("searchGroupList", groupList);
		return ResultMapHelper.success(dataMap);
	}

	public Map<String, Object> down(Map<String, Object> map) {
		map.put("pageSize", "5000");
		Map<String, Object> resutlMap = report(1, map,true);
		Page<AkjCallClueStatisticsVo> page = (Page<AkjCallClueStatisticsVo>) resutlMap.get("data");
		List<AkjCallClueStatisticsVo> list = page.getContent();
		String str = CsvUtils.doExport(false, reportList);
		if (!CollectionUtils.isEmpty(list)) {
			for (AkjCallClueStatisticsVo vo : list) {
				Long clueTotle = vo.getClueTotal();
				Long netCalledTotal = vo.getNetCalledTotal();
				Long noCallTotal = 0L;
				if (clueTotle != null && netCalledTotal != null) {
					noCallTotal = clueTotle - netCalledTotal;
					noCallTotal = noCallTotal > 0 ? noCallTotal : 0;
				}
				str += CsvUtils.doExport(false, vo.getStatDate(), vo.getName(), parseString(vo.getClueTotal()),
						parseString(vo.getCallTime()), parseString(vo.getCalledTotal()),
						parseString(vo.getNetCalledTotal()), noCallTotal + "", parseString(vo.getConnectTotal()),
						parseString(vo.getUnConnectTotal()), parseString(vo.getUnConfirmTotal()),
						parseString(vo.getConfirmTotal()), parseString(vo.getWaitTotal()));
			}
		}
		return ResultMapHelper.success(str);
	}

	private String parseString(Long value) {
		if (value == null) {
			return "0";
		}
		return value + "";
	}

}
